package Classification

import (
	"OnlineRetailers/controllers/admin/PageNum"
	session2 "OnlineRetailers/controllers/admin/session"
	"OnlineRetailers/controllers/errorDeal"
	"OnlineRetailers/models"
	"OnlineRetailers/models/Admin"
	"OnlineRetailers/models/Admin/resMes"
	error2 "OnlineRetailers/models/errorDeal"
	"fmt"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/orm"
	"strconv"
)

type GetClassification struct {
	beego.Controller
}

func (c *GetClassification) GetClassification() {
	defer func() {
		c.Ctx.Output.Header("Access-Control-Allow-Origin", "*")
		c.Ctx.Output.Status = 200
		c.ServeJSON()
	}()
	var addr = "/Classification/GetClassification"
	res := resMes.GetClassification{}
	classifications := []*Admin.Classification{}
	log := &error2.Log{}
	var err error
	var show = ""

	o := orm.NewOrm()
	Page, err := c.GetInt("Page", 0)
	begin, err := c.GetInt("begin", 0)
	if err != nil {
		c.Data["json"] = errorDeal.ErrMess(log, "400", err, addr, err.Error())
		return
	}
	limit := " limit " + strconv.Itoa(models.AdminPage) + " offset " + strconv.Itoa(models.AdminPage*Page)
	////fmt.Println(begin)
	if begin == 0 {

		err = session2.CheckSession(c.Ctx.Request.Header["Session"], 1)
		if err != nil {
			c.Data["json"] = errorDeal.ErrMess(log, "400", err, addr, err.Error())
			return
		}
		count, err := PageNum.GetPageNum("classification", o)
		if err != nil {
			c.Data["json"] = errorDeal.ErrMess(log, "400", err, addr, "GetPageNum"+err.Error())
			return
		}
		res.Count = count / models.AdminPage
	} else {
		show = "where `show`=1"
		limit = ""
	}

	sql := "select * from `classification` " + show + " order by `classification_id` desc" + limit
	_, err = o.Raw(sql).QueryRows(&classifications)

	if err != nil {
		c.Data["json"] = errorDeal.ErrMess(log, "400", err, addr, err.Error())
		return
	}
	fmt.Println(begin)
	if begin == -1 {
		sql = "select * from `product_detailed` left join `classification_product_detaileds` on `product_detailed`.`product_id`=`classification_product_detaileds`.`product_detailed_id` where `classification_product_detaileds`.`classification_id`=? limit ?"

	} else {
		sql = "select * from `product_detailed` left join `classification_product_detaileds` on `product_detailed`.`product_id`=`classification_product_detaileds`.`product_detailed_id` where `classification_product_detaileds`.`classification_id`=?"

	}
	for i := 0; i < len(classifications); i++ {
		if begin == -1 {
			_, err = o.Raw(sql, classifications[i].ClassificationId, models.DateLengthByClass).QueryRows(&classifications[i].ProductDetailed)

		} else {
			_, err = o.Raw(sql, classifications[i].ClassificationId).QueryRows(&classifications[i].ProductDetailed)

		}
		if err != nil {
			c.Data["json"] = errorDeal.ErrMess(log, "400", err, addr, err.Error())
			return
		}
	}

	res.Classification = classifications
	res.Code = "200"
	c.Data["json"] = res

}
